package com.liangwj.springbootweb.configuration;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;
import java.io.IOException;

/**
 * <b>Description:</b> Mybatis-多数据源配置 <br/>
 * @author Lingwenjun
 * @date 2019/1/3-18:06
 * @version 1.0
 */
@Configuration
//这块的注解就是指明了扫描dao层，并且给dao层注入指定的SqlSessionTemplate。所有@Bean都需要按照命名指定正确。
@MapperScan(basePackages = {"com.liangwj.springbootweb.mapper.primaryDB"}, sqlSessionTemplateRef = "primarySqlSessionTemplate")
public class MybatisMutilDataSourceConfig {

    //首先创建DataSource
    @Bean(name = "primaryDataSource")
    @Primary//指定主库
    @ConfigurationProperties(prefix = "spring.datasource.primary")
    public DataSource buildDataSource() {
        return DataSourceBuilder.create().build();
    }

    //然后创建SqlSessionFactory
    @Bean(name = "primarySqlSessionFactory")
    @Primary
    public SqlSessionFactory primarySqlSessionFactory(@Qualifier("primaryDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
//        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:resources/mapping/primary/*.xml"));
        return bean.getObject();
    }

    //再创建事务
    @Bean(name = "primaryTransactionManager")
    @Primary
    public DataSourceTransactionManager transactionManager(@Qualifier("primaryDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    //最后包装到SqlSessionTemplate中。其中需要指定分库的mapper文件地址，以及分库dao层代码
    @Bean(name = "primarySqlSessionTemplate")
    @Primary
    public SqlSessionTemplate primarySqlSessionTemplate(@Qualifier("primarySqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }


}
